package servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dataTypes.*;

/*
 * Gets by params to display to user
 */

@SuppressWarnings("serial")
public class CoupoNowServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setContentType("text/html");
			//appManager.getInstance().getByParam();
			// build query to sent to appManager
			//List<deal> result = appManager.getInstance().getDeals(q);	
			// send back to client

			//appManager.getInstance().sendEmail("yoavbar99@gmail.com", 8976892673L);
			//Google Lgin to get Auth TOken:
			//response.getWriter().println(C2DMRegisterWithGoogle.register());

			//AuthTOken GETTER CHECK
			//response.getWriter().println(appManager.getInstance().getAuthToken());

			//CHECK IF GETTING USERDEVICES FROM DB WORKS
			/*List<userDevice> users = appManager.getInstance().getUsers();
			for (userDevice usr :users) {
				if (!usr.getGoogleName().equals("OURACCOUNT"))
					response.getWriter().println(usr.getDeviceRegistrationID());
			}*/
			List<userDevice> users = appManager.getInstance().getUsers();
			for (userDevice usr :users) {
				if (!usr.getGoogleName().equals("OURACCOUNT")){
					response.getWriter().println(usr.getGoogleName());
					response.getWriter().println(usr.getDeviceRegistrationID());
					response.getWriter().println(sendMessage(usr));
				}	}


		} catch (Exception e) { 
			e.printStackTrace();
		}		

	}


	private String sendMessage(userDevice user){
		try {
			StringBuilder dataToSend = new StringBuilder();
			dataToSend.append("registration_id=").append(URLEncoder.encode(user.getDeviceRegistrationID(), "UTF-8"));
			dataToSend.append("&collapse_key=").append(URLEncoder.encode("replace-existing", "UTF-8"));

			byte[] dataToSendByte = dataToSend.toString().getBytes("UTF-8");

			URL url = new URL("https://android.apis.google.com/c2dm/send");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Authorization", "GoogleLogin auth=" + appManager.getInstance().getAuthToken());

			OutputStream out = conn.getOutputStream();
			out.write(dataToSendByte);
			out.close();

			InputStream inputStream;

			int responseCode = conn.getResponseCode();
			if (responseCode == HttpServletResponse.SC_UNAUTHORIZED ||
					responseCode == HttpServletResponse.SC_FORBIDDEN) { 
				return "if 1 " + conn.getResponseMessage() + conn.getResponseCode();
			}

			if (responseCode == HttpServletResponse.SC_OK){
				inputStream = conn.getInputStream();
				String responseMessage = conn.getResponseMessage();
				if (responseMessage.contains("Error")){
					return "if 2 " + conn.getResponseMessage() + conn.getResponseCode();
				}
				else {
					return " else " + conn.getResponseMessage() + conn.getResponseCode()+ "   " + toString(inputStream);
				}
			}			
		}
		catch (Exception e) {
			// TODO Autos-generated catch block
			e.printStackTrace();
		}
		return null;
	}	


	private static String toString(InputStream inputStream) throws IOException {
		String string;
		StringBuilder outputBuilder = new StringBuilder();
		if (inputStream != null) {
			BufferedReader reader =
				new BufferedReader(new InputStreamReader(inputStream));
			while (null != (string = reader.readLine())) {
				outputBuilder.append(string).append('\n');
			}
		}
		return outputBuilder.toString();
	}

	private static String parseToken(String resp){	
		StringTokenizer st = new StringTokenizer(resp, "=\n ");
		String finalToken= null;
		while(st.hasMoreElements()){
			if (st.nextToken().equals("Auth")){
				if (st.hasMoreElements())
					finalToken = st.nextToken();
				break;
			}

		}
		return finalToken;
	}


	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}




